package zozopo.business;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import zozopo.operations.business.AdOS;
import zozopo.operations.business.AdTB;
import zozopo.operations.business.IPReportOS;
import zozopo.operations.business.IPReportTB;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

public class AdAction extends ActionSupport implements Action ,ServletRequestAware,ServletResponseAware{
	
	/**
	 * 
	 */
	
	private static final Log logger = LogFactory.getLog(ActionSupport.class);
	
	private static final long serialVersionUID = 1L;
	private String id;
	
	HttpServletRequest request;
	HttpServletResponse response;
	
	public String execute(){
		
		
		
		AdOS adOS = new AdOS();
		//AdTB ad = new AdTB();
		
		IPReportOS ipReportOS = new IPReportOS(adOS.getConn());
		IPReportTB ipreport = new IPReportTB();
		
		try {
			
			adOS.views(id);
			AdTB ad = adOS.getAdById(id);

			ipreport.setName_ipreport(ad.getName_ad());
			ipreport.setUrl_ipreport(ad.getUrl_ad());
			ipreport.setIp_ipreport(getIpAddr(request));
			ipReportOS.insertReport(ipreport);

			response.sendRedirect(ad.getUrl_ad());
			
		}catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			adOS.releaseConnection();
		}
		
		return NONE;
	}

	public void setServletRequest(HttpServletRequest arg0) {
		// TODO Auto-generated method stub
		request = arg0;
	}

	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		response = arg0;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	/**
     * 获得客户端真是ip
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");    
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
            ip = request.getHeader("Proxy-Client-IP");    
        }    
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
            ip = request.getHeader("WL-Proxy-Client-IP");    
        }    
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
            ip = request.getRemoteAddr();    
     }
		return ip; 
    }
}
